//
//  LoginViewController.m
//  BiologyLibrary
//
//  Created by milo on 16/7/1.
//  Copyright © 2016年 youxh. All rights reserved.
//

#import "LoginViewController.h"
#import "User.h"
#import "ServiceUser.h"
@interface LoginViewController ()

@end

@implementation LoginViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
    [self hideNaviBar:YES];
    
    headView.layer.cornerRadius=15;
    headView.clipsToBounds=YES;
    headView.backgroundColor=[UIColor clearColor];
    headView.image=[UIImage imageNamed:@"appicon"];
    btnLogin.backgroundColor = [UIColor colorWithRed:255.0/255.0 green:255.0/255.0 blue:255.0/255.0 alpha:0.8];
    selectuserbtn.layer.cornerRadius=11;
    selectuserbtn.clipsToBounds=YES;

    if (bIsiPhone5) {
        btnLogin.layer.cornerRadius=18;
    }else if (bIsiPhone6){
        btnLogin.layer.cornerRadius=20;

    }else if (bIsiPhone6p){
        btnLogin.layer.cornerRadius=24;
        
    }if (bIsiPhone4) {

        btnLogin.layer.cornerRadius=15;
        headView.autoresizingMask=NO;
        headView.frame=CGRectMake(118, 68, 85, 85);
        [self.view addSubview:headView];
    }
    if ([[UIScreen mainScreen] bounds].size.height==480) {

        btnLogin.layer.cornerRadius=15;
        headView.autoresizingMask=NO;
        headView.frame=CGRectMake(118, 68, 85, 85);
        [self.view addSubview:headView];

    }

    btnLogin.clipsToBounds=YES;
    [btnLogin addTarget:self action:@selector(btnLoginClick)
       forControlEvents:UIControlEventTouchUpInside];
    
    if(![[NSUserDefaults standardUserDefaults] boolForKey:@"firstStart"]){
        [[NSUserDefaults standardUserDefaults] setBool:YES forKey:@"firstStart"];
        NSLog(@"第一次启动");
        [self getuserlist:nil];
        
    }else{
    }
}
-(IBAction)getuserlist:(UIButton*)sender{
    [self.view makeToastActivityWithMessage:@"更新数据。。。"];
    self.view.userInteractionEnabled=NO;
    NSDictionary *parametersDict = [NSDictionary dictionaryWithObjectsAndKeys:
                                    @"",@"",nil];
    AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
    //    // 设置超时时间
    [manager.requestSerializer willChangeValueForKey:@"timeoutInterval"];
    manager.requestSerializer.timeoutInterval = 15.f;
    [manager.requestSerializer didChangeValueForKey:@"timeoutInterval"];
    __weak typeof(self) weakSelf = self;
    [manager POST:[NSString stringWithFormat:@"%@getUserList.do",APPDelegate.baseUrl]
       parameters:parametersDict
          success:^(AFHTTPRequestOperation *operation, id responseObject) {
              [weakSelf loadAllSampleNo];
              NSLog(@"responseObject %@",responseObject);
              if([responseObject isKindOfClass:[NSDictionary class]] && [[responseObject allKeys] containsObject:@"error"]){
                  [self.view hideToastActivityWithError:[responseObject objectForKey:@"error"] completion:nil];
                  
              }else{
                  userarr=[NSMutableArray arrayWithArray:[responseObject objectForKey:@"getUserList"]];
                  if ([userarr isKindOfClass:[NSNull class]]||userarr.count==0) {
                      self.view.userInteractionEnabled=YES;
                      
                      return ;
                  }else{
                      [ServiceUser clearTable];
                      [self performSelector:@selector(saveserviceUser) withObject:nil afterDelay:2];
                  }
                  
              }
              

        } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
              self.view.userInteractionEnabled=YES;
              
              DLog(@"operation %@",operation.responseString);
              if ([error code] == 1) {
                  
                  [self.view hideToastActivityWithError:d_Error_NetWork completion:nil];
              }else if([error code] == 2){
                  
                  [self.view hideToastActivityWithError:d_Error_TimeOut completion:nil];
              }else{
                  
                  [self.view hideToastActivityWithError:d_Error_UnKnow completion:nil];
              }
          }];

    
}

-(void)loadAllSampleNo
{
    AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
    //    // 设置超时时间
    [manager.requestSerializer willChangeValueForKey:@"timeoutInterval"];
    manager.requestSerializer.timeoutInterval = 15.f;
    [manager.requestSerializer didChangeValueForKey:@"timeoutInterval"];
    __weak typeof(self) weakSelf = self;
    [manager GET:[NSString stringWithFormat:@"%@getSampleNOList.do",APPDelegate.baseUrl] parameters:nil success:^(AFHTTPRequestOperation *operation, id responseObject) {
        [[NSUserDefaults standardUserDefaults] setObject:responseObject forKey:@"onlineData"];
        [[NSUserDefaults standardUserDefaults] synchronize];
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        
    }];
}
-(void)saveserviceUser{
    for (int i=0; i<userarr.count; i++) {
        NSDictionary*temp=[userarr objectAtIndex:i];
        NSString*usertype=[NSString stringWithFormat:@"%@",[temp objectForKey:@"usertype"]];
        if (![usertype isEqualToString:@"2"]) {
            ServiceUser *serviceuser = [[ServiceUser alloc] init];
            serviceuser.username = [NSString stringWithFormat:@"%@",[temp objectForKey:@"username"]];
            serviceuser.password = [NSString stringWithFormat:@"%@",[temp objectForKey:@"password"]];
            serviceuser.authority = [NSString stringWithFormat:@"%@",[temp objectForKey:@"authority"]];
            serviceuser.userid = [NSString stringWithFormat:@"%@",[temp objectForKey:@"id"]];
            serviceuser.isMan = [NSString stringWithFormat:@"%@",[temp objectForKey:@"isMan"]];
            serviceuser.telphone = [NSString stringWithFormat:@"%@",[temp objectForKey:@"telphone"]];
            serviceuser.usertype = [NSString stringWithFormat:@"%@",[temp objectForKey:@"usertype"]];
            serviceuser.positinal = [NSString stringWithFormat:@"%@",[temp objectForKey:@"positinal"]];
            serviceuser.displayname = [NSString stringWithFormat:@"%@",[temp objectForKey:@"displayname"]];

            
            dispatch_async(dispatch_get_global_queue(0, 0), ^{
                [serviceuser save];
            });

        }
        
    }
    
    [self getpeizhiarr];
}
-(void)getpeizhiarr{
    self.view.userInteractionEnabled=NO;
    NSDictionary *parametersDict = [NSDictionary dictionaryWithObjectsAndKeys:
                                    @"-1",@"type",nil];
    AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
    //    // 设置超时时间
    [manager.requestSerializer willChangeValueForKey:@"timeoutInterval"];
    manager.requestSerializer.timeoutInterval = 15.f;
    [manager.requestSerializer didChangeValueForKey:@"timeoutInterval"];
    
    [manager POST:[NSString stringWithFormat:@"%@getConfigList.do",APPDelegate.baseUrl]
       parameters:parametersDict
          success:^(AFHTTPRequestOperation *operation, id responseObject) {
              
              DLog(@"responseObject %@",responseObject);
              if([responseObject isKindOfClass:[NSDictionary class]] && [[responseObject allKeys] containsObject:@"error"]){
                  [self.view hideToastActivityWithError:[responseObject objectForKey:@"error"] completion:nil];
                  
              }else{
                  NSArray*allarr=[NSArray arrayWithArray:responseObject];
                  NSLog(@"arrrrr======%@",allarr);
                  NSMutableArray*bookarr=[[NSMutableArray alloc]init];
                  NSMutableArray*wenduarr=[[NSMutableArray alloc]init];
                  NSMutableArray*timearr=[[NSMutableArray alloc]init];
                  NSMutableArray*speedarr=[[NSMutableArray alloc]init];
                  NSMutableArray*jiqiarr=[[NSMutableArray alloc]init];
                  NSMutableArray*bxareaarr=[[NSMutableArray alloc]init];
                  NSMutableArray*ydareaarr=[[NSMutableArray alloc]init];
                  for (int i=0; i<allarr.count; i++) {
                      NSDictionary*temp=[allarr objectAtIndex:i];
                      NSString*type=[NSString stringWithFormat:@"%@",[temp objectForKey:@"type"]];
                      NSString*configeCon=[NSString stringWithFormat:@"%@",[temp objectForKey:@"configCon"]];
                      if ([type isEqualToString:@"0"]) {
                          [bookarr addObject:configeCon];
                      }if ([type isEqualToString:@"1"]) {
                          NSString*setype=[NSString stringWithFormat:@"%@",[temp objectForKey:@"secondType"]];
                          if ([setype isEqualToString:@"0"]) {
                              [speedarr addObject:configeCon];
                          }if ([setype isEqualToString:@"1"]) {
                              [timearr addObject:configeCon];

                          }if ([setype isEqualToString:@"2"]) {
                              [wenduarr addObject:configeCon];

                          }
                      }if ([type isEqualToString:@"2"]) {
                          [jiqiarr addObject:configeCon];

                      }if ([type isEqualToString:@"3"]) {
                          [ydareaarr addObject:configeCon];

                      }if ([type isEqualToString:@"4"]) {
                          [bxareaarr addObject:configeCon];

                      }
                      
                      
                  }
                  [APPDataCenter savebookidarr:bookarr lixingarr:jiqiarr wenduarr:wenduarr timearr:timearr speedarr:speedarr bxareaarr:bxareaarr ydareaarr:ydareaarr];
                  [self.view hideToastActivityWithSuccess:@"更新完成" completion:nil];

              }
              
              
          } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
              self.view.userInteractionEnabled=YES;
              
              DLog(@"operation %@",operation.responseString);
              if ([error code] == 1) {
                  
                  [self.view hideToastActivityWithError:d_Error_NetWork completion:nil];
              }else if([error code] == 2){
                  
                  [self.view hideToastActivityWithError:d_Error_TimeOut completion:nil];
              }else{
                  
                  [self.view hideToastActivityWithError:d_Error_UnKnow completion:nil];
              }
          }];

}
-(void)btnLoginClick{
    
    
    if ((usernamefield.text.length == 0)) {
        [self.view makeToast:@"用户名不能为空" position:@"center"];
        return;
    }
    
    if (Psdfield.text.length == 0) {
        [self.view makeToast:@"密码不能为空" position:@"center"];
        return;
    }
    
    ServiceUser *userInDB = [ServiceUser findFirstWithFormat:@" WHERE %@ = '%@' ",@"username", usernamefield.text];
    if (userInDB){
        if (![Psdfield.text isEqualToString:userInDB.password]) {
            [self.view hideToastActivityWithError:@"密码错误！" completion:nil];
            return;
        }else{
            [DataManage saveObject:usernamefield.text forKey:@"phone"];
            User *userInDB2 = [User findFirstWithFormat:@" WHERE %@ = '%@' ",@"name", usernamefield.text];
             if(!userInDB2){
                 User *user = [[User alloc] init];
                 user.name = usernamefield.text;
                 user.password = Psdfield.text;
                 dispatch_async(dispatch_get_global_queue(0, 0), ^{
                     [user save];
                 });
             }
            [APPDataCenter saveUserName:userInDB.username password:userInDB.password authority:userInDB.authority isMan:userInDB.isMan telphone:userInDB.telphone displayname:userInDB.displayname usertype:userInDB.usertype userid:userInDB.userid positinal:userInDB.positinal];
            
            [APPDelegate loginSuccess];

        }

    }else{
        [self.view makeToast:@"用户名不存在" position:@"center"];

    }
    
    
    
    NSLog(@"Serviceuser===%@",[ServiceUser findAll]);
    NSLog(@"user===%@",[User findAll]);

}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}
-(IBAction)selectuser:(UIButton *)sender{
    
    UserListViewController *userListVC = [[UserListViewController alloc] init];
    userListVC.delegate = self;
    [self presentViewController:userListVC animated:YES completion:nil];
    
}
#pragma mark - UserListViewControllerDelegate
-(void)userListDidSelectedUser:(User *)user{
    
    usernamefield.text = user.name;
    Psdfield.text = user.password;
}

@end
